package com.zycx.system.user.service;

import com.zycx.common.entity.CamelMap;
import com.zycx.common.entity.EntityUtils;
import com.zycx.common.result.ServerResponse;
import com.zycx.system.user.entity.User;
import com.zycx.system.user.mapper.UserMapper;
import com.zycx.interceptor.JjwtCreateToken;
import com.zycx.system.user.utils.PassWordToHash;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Description:
 * Created by zycx on 2018-12-04 21:37
 * Created with IntelliJ IDEA.
 */
@Service
@Slf4j
public class UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 添加用户
     *
     * @param user 用户
     * @return 用户
     */
    public ServerResponse saveUser(User user) {
        CamelMap byUserName = userMapper.findByUserName(user.getUserName());
        if (byUserName != null) {
            return ServerResponse.errorMessage("用户名已经存在");
        }
        String passWord = PassWordToHash.passwordToHash(user.getPassWord());
        user.setPassWord(passWord);
        user.setId(EntityUtils.getId());
        user.setSuperAdmin("0");
        if (user.getName() == null) {
            user.setName(user.getUserName());
        }
        user.setStatus("0");
        user.setCtrTime(new Date());
        int insert = userMapper.insert(user);
        if (insert == 0) {
            return ServerResponse.error();
        }
        return ServerResponse.successData(user);
    }

    /**
     * 登陆
     *
     * @param user 用户
     * @return 用户 token
     */
    public ServerResponse login(User user) {
        CamelMap userInDataBase = userMapper.findByUserName(user.getUserName());
        if (userInDataBase == null) {
            return ServerResponse.errorMessage("用户不存在,请先注册用户");
        }
        if (!PassWordToHash.comparePassWord(user.getPassWord(), userInDataBase.get("passWord").toString())) {
            return ServerResponse.errorMessage("密码错误");
        } else {
//            String token = JjwtCreateToken.getToken(userInDataBase);
//            userInDataBase.put("token", token);
            String jjwtToken = "";
            JjwtCreateToken jjwtCreateToken = new JjwtCreateToken();
            try {
                jjwtToken = jjwtCreateToken.createJJWTToken(userInDataBase.get("id"), String.valueOf(userInDataBase));
            } catch (Exception e) {
                throw new RuntimeException("生成 token 失败");
            }
            userInDataBase.put("token", jjwtToken);
            return ServerResponse.successData(userInDataBase);
        }
    }


}
